# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

u"""

Loggers used in pyLot are subdivided in main packages : core, qtgui, dataconverter, ...

A special logger, pyLot.plugins, is used when a message or error is due to a problem in a plugin or
due to an incomplete/missing plugin but raised by pyLot library.
"""

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = ['StatusBarLoggingHandler', 'init_loggers',
           'LOGGING_FORMATTER_STD', 'LOGGING_HANDLER_STDOUT',
           'log_exception']

import logging


LOGGING_FORMATTER_STD = logging.Formatter('%(pathname)s:%(lineno)d, func:%(funcName)s: [ %(levelname)-6s] %(message)s')

#try :
#  from dhexternal.logutils.colorize import ColorizingStreamHandler
#except ImportError :
LOGGING_HANDLER_STDOUT = logging.StreamHandler()
#else :
#  LOGGING_HANDLER_STDOUT = ColorizingStreamHandler()

LOGGING_HANDLER_STDOUT.setFormatter(LOGGING_FORMATTER_STD)

# ATTENTION : problème pour installation système
#LOGGING_HANDLER_FILE = logging.FileHandler('%s.log' % __file__.replace('.py', ''), 'w')
#LOGGING_HANDLER_FILE.setFormatter(LOGGING_FORMATTER_STD)

#LOGGER.addHandler(LOGGING_HANDLER_FILE)

def init_loggers(logger_names, handler=LOGGING_HANDLER_STDOUT, level=logging.INFO):
  for logger_name in logger_names :
    logger = logging.getLogger(logger_name)
    logger.setLevel(level)
    logger.addHandler(handler)

def log_exception(error):
  return u'**Python Exception** %s: %s' % (type(error).__name__, error)

class StatusBarLoggingHandler(logging.Handler):
  def __init__(self, status_bar):
    u"""
    A special logging handler for QStatusBar.
    
    status_bar: Qt QStatusBar or class with showMessage(msg, timeout) method.
    """
    self.statusbar = status_bar
    logging.Handler.__init__(self)

  def flush(self):
      """
      Flushes the stream.
      """
      pass

  def emit(self, record):
    """
    Emit a record.

    If a formatter is specified, it is used to format the record.
    The record is then written to the stream with a trailing newline.  If
    exception information is present, it is formatted using
    traceback.print_exception and appended to the stream.  If the stream
    has an 'encoding' attribute, it is used to determine how to do the
    output to the stream.
    """
    try:
      msg = self.format(record)
      if isinstance(msg, unicode):
        self.statusbar.showMessage(msg, 5000)
      else:
        pass
      self.flush()
    except:
      self.handleError(record)
